package com.uinnova.springboot.asynchronization;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

@RestController
@Api
public class AsyncController {

    @Autowired
    private MsgService msgService;

    @GetMapping(value = "/jail/sync")
    @ApiOperation(value = "测试同步")
    public void testSync() throws InterruptedException {
        msgService.sync();
        msgService.syncAfter();
    }

    @ApiOperation(value = "测试异步")
    @GetMapping(value = "/jail/async")
    public void testAsync() throws InterruptedException {
        msgService.async();
        msgService.asyncAfter();
    }

    @GetMapping(value = "/jail/async/noret")
    public Map<String, Object> getAsyncNoRet() throws Exception {
        Map<String, Object> stringObjectMap = new HashMap<>(16);
        msgService.sendA();
        msgService.sendB();
        stringObjectMap.put("success", true);
        return stringObjectMap;
    }

    @GetMapping(value = "/jail/async/ret")
    public Map<String, Object> getAsyncRet() throws Exception {
        Map<String, Object> ret = new HashMap<>(16);
        Future<String> sendC = msgService.sendC();
        Future<String> sendD = msgService.sendD();
        String sendCRet = sendC.get(5000, TimeUnit.MILLISECONDS);
        String sendDRet = sendD.get(5000, TimeUnit.MILLISECONDS);
        ret.put("success", true);
        ret.put("sendC", sendCRet);
        ret.put("sendD", sendDRet);
        return ret;
    }

}
